package com.zhentao.subscription.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.subscription.common.R;
import com.zhentao.subscription.domain.dto.TemplateDTO;
import com.zhentao.subscription.domain.entity.SubscriptionTemplate;
import com.zhentao.subscription.service.TemplateService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/subscription/templates")
@CrossOrigin(origins = "http://localhost:5173")
public class TemplateController {

    private final TemplateService templateService;

    public TemplateController(TemplateService templateService) {
        this.templateService = templateService;
    }

    @PostMapping
    public R<Long> save(@Valid @RequestBody TemplateDTO dto) {
        SubscriptionTemplate t = new SubscriptionTemplate();
        t.setId(dto.getId());
        t.setName(dto.getName());
        t.setScopeType(dto.getScopeType());
        t.setSubscribeMode(dto.getSubscribeMode());
        t.setDataFormat(dto.getDataFormat());
        t.setDataSource(dto.getDataSource());
        t.setGroupFields(dto.getGroupFields() == null ? null : String.join(",", dto.getGroupFields()));
        t.setNumericAggFields(dto.getNumericAggFields());
        t.setConditions(dto.getConditions());
        t.setSelectedFields(dto.getSelectedFields() == null ? null : String.join(",", dto.getSelectedFields()));
        LocalDateTime now = LocalDateTime.now();
        t.setUpdatedTime(now);
        if (t.getId() == null) {
            t.setCreatedTime(now);
        }
        templateService.saveOrUpdate(t);
        return R.ok(t.getId());
    }

    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable Long id) {
        templateService.removeById(id);
        return R.ok();
    }

    @GetMapping
    public R<Page<SubscriptionTemplate>> page(@RequestParam(defaultValue = "1") int pageNo,
                                              @RequestParam(defaultValue = "10") int pageSize,
                                              @RequestParam(required = false) String keyword) {
        LambdaQueryWrapper<SubscriptionTemplate> qw = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isBlank()) {
            qw.like(SubscriptionTemplate::getName, keyword);
        }
        qw.orderByDesc(SubscriptionTemplate::getUpdatedTime);
        Page<SubscriptionTemplate> page = templateService.page(new Page<>(pageNo, pageSize), qw);
        return R.ok(page);
    }

    @GetMapping("/{id}")
    public R<SubscriptionTemplate> getById(@PathVariable Long id) {
        return R.ok(templateService.getById(id));
    }
}

